package com.mdd.service.ekyt.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.teautil.models.RuntimeOptions;
import com.antgroup.antchain.openapi.securitytech.Client;
import com.antgroup.antchain.openapi.securitytech.models.Config;
import com.antgroup.antchain.openapi.securitytech.models.QueryEkytDriverRequest;
import com.antgroup.antchain.openapi.securitytech.models.QueryEkytDriverResponse;
import com.antgroup.antchain.openapi.securitytech.models.RequestHead;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mdd.service.ekyt.EkytDriverService;
import com.mdd.utils.HexUtil;
import com.mdd.vo.ekyt.EkytInfoVo;
import com.mdd.vo.ekyt.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

/**
 * 阿里风控接口
 *   风控密钥
 *   AC5Ssgi3rduJaGrH
 *   GTvxkS3EhjsX2SgkT3WuTnZq9YMQQAXY
 * <p>
 *   评分免押标准：0-10免押金，10-30，押金50%，30以上100%押金
 * {@code @Description}
 * @Author 幻速
 * {@code @Date} 2023/10/31 14:40
 **/
@Slf4j
@Service
public class EkytDriverServiceImpl implements EkytDriverService {

    @Override
    public EkytInfoVo queryEkytDriverEx(UserInfo userInfo) throws Exception {
        String aesKey = "62313332E56730A32FD41B02A5CB47C6";

        Config config = new Config()
                .setAccessKeyId("AC5Ssgi3rduJaGrH")
                .setAccessKeySecret("GTvxkS3EhjsX2SgkT3WuTnZq9YMQQAXY")
                .setEndpoint("openapi.antchain.antgroup.com")
                .setProtocol("HTTP");
        Client client = new Client(config);
        // header 公共参数：指定RaaS产品
        String extData = "{\"raas_products\":\"" + "ekyt-driver-identity-verify" + "\"}";
        Map<String, String> header = new HashMap<>();
        header.put("X-AntCloud-Gw-Ext-Flag", extData);

        //参数加密
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(userInfo));
        String requestStr = jsonSortToStr(jsonObject.toJSONString(), "&", "=");
        log.info("加密前：requestStr------>"+requestStr);
        SecretKeySpec keySpec = new SecretKeySpec(Objects.requireNonNull(HexUtil.hexStrToByte(aesKey)), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec ivSpec = new IvParameterSpec(new byte[16]);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec,ivSpec);
        byte[] bytes = new byte[0];
        if (requestStr != null) {
            bytes = cipher.doFinal(requestStr.getBytes(StandardCharsets.UTF_8));
        }
        requestStr = HexUtil.byteToHexStr(bytes);
        log.info("加密后：requestStr--------------->"+requestStr);


        String requestId="101"+System.currentTimeMillis();
        RequestHead head = new RequestHead();
        head.setRequestId(requestId);
        head.setProductCode("RDDB04201PR");
        head.setSecretId("RvOBRwrX9YLGxvrZQkr25pCih6svCFGIR7HNibXen9E=");
        //签名加密
        jsonObject.put("requestId",head.getRequestId());
        jsonObject.put("secretId",head.getSecretId());
        jsonObject.put("productCode",head.getProductCode());
        String signStr = jsonSortToStr(jsonObject.toJSONString(), "&", "=");
        log.info("加密前：signStr--------------->"+signStr);
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec keySpec2 = new SecretKeySpec(Objects.requireNonNull(HexUtil.hexStrToByte(aesKey)), "HmacSHA256");
        mac.init(keySpec2);
        if (signStr != null) {
            bytes = mac.doFinal(signStr.getBytes(StandardCharsets.UTF_8));
        }
        //签名
        signStr = HexUtil.byteToHexStr(bytes);
        log.info("加密后：signStr--------------->"+signStr);

        // 构建参数
        QueryEkytDriverRequest request = new QueryEkytDriverRequest();
        request.setHead(head);
        request.setRequest(requestStr);
        request.setSignature(signStr);

        // 发起请求
        QueryEkytDriverResponse response = client.queryEkytDriverEx(request, header, new RuntimeOptions());
        log.info("QueryEkytDriverResponse------->"+JSON.toJSONString(response));
        // 解析结果
        // 判断结果码
        if (!"00000".equals(response.getResultCode())) {
            throw new RuntimeException(response.getResultMsg());
        }
        SecretKeySpec secretKey = new SecretKeySpec(Objects.requireNonNull(HexUtil.hexStrToByte(aesKey)), "AES");
        Cipher cipher1 = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec ivSpec1 = new IvParameterSpec(new byte[16]);
        cipher1.init(Cipher.DECRYPT_MODE, secretKey, ivSpec1);
        byte[] decryptedBytes = cipher1.doFinal(Objects.requireNonNull(HexUtil.hexStrToByte(response.getData().getBizRes())));
        return new ObjectMapper().readValue(decryptedBytes, EkytInfoVo.class);
    }
    /**
     *  将json数据排序后，拼接成字符串
     * @param jsonStr 需要转换对象
     * @param join1 =
     * @param join2 &
     * @return 转换后字符串
     */
    public static String jsonSortToStr (String jsonStr, String join1, String join2) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Map map = objectMapper.readValue(jsonStr, Map.class);
            // 使用 TreeMap 对 Map 中的键进行排序
            Map<String, Object> sortedMap = new TreeMap<>(map);

            // 构建查询字符串
            StringBuilder str = new StringBuilder();
            for (Map.Entry<String, Object> entry : sortedMap.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue().toString();

                // 拼接 "key=value&" 形式的键值对
                str.append(key).append(join2).append(value).append(join1);
            }

            // 去除末尾的 "&" 符号
            if (str.length() > 0) {
                str.setLength(str.length() - 1);
            }
            return str.toString();
        } catch (JsonProcessingException e) {
            return null;
        }
    }
    /**
     * 将字符串按照分隔符进行切分，然后转换为json对象
     * @param str
     * @param split1
     * @param split2
     * @return
     */
    public static String strToJson (String str, String split1, String split2) {
        try {
            // 将字符串按照split1 分割成键值对数组
            String[] keyValuePairs = str.split(split1);

            // 创建 Map 对象存储键值对
            Map<String, String> map = new HashMap<>();

            // 遍历键值对数组
            for (String pair : keyValuePairs) {
                // 将每个键值对按照 '=' 分割成键和值
                String[] keyValue = pair.split(split2);
                if (keyValue.length == 2) {
                    String key = keyValue[0];
                    String value = keyValue[1];
                    map.put(key, value);
                }
            }

            // 将 Map 对象转换为 JSON 对象
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(map);

            return json;
        } catch (JsonProcessingException e) {
            return null;
        }
    }
}
